<?php

namespace Console\Logic;

use \Common\Logic\BaseLogic;

/**
 * 数据备份控制器
 */
class BackupsLogic extends BaseLogic {

    private $colorModel;
    private $eyeModel;
    private $sysinfoModel;
    private $pigeonModel;

    public function __construct() {
        parent::__construct();
        $this->colorModel = D('ColorDic');
        $this->eyeModel = D('EyeDic');
        $this->sysinfoModel = D('Sysinfo');
        $this->pigeonModel = D('Pigeon');
    }
    
    public function toSql($path = "") {
        header("Content-Type:text/html; charset=utf-8");

        if (empty($path)) {
            $path = WEB_PATH . "/Backups/" . date("Y-m-d", time());
        }
        is_dir($path) or mkdir($path, 0777, true);

        $dbConf = C("MYSQL_DB_CONFIG");
        $dbname = $dbConf["DB_NAME"];

        $model = D('Pigeon');
        $rs = $model->query("SHOW TABLES FROM " . $dbname);

        $tableList = array();
        foreach ($rs as $value) {
            foreach ($value as $v) {
                $tableList[] = $v;
            }
        }

        $fileName = $path . "/" . date("H_i_s", time()) . ".sql";

        /**
         * 数据结构语句
         */
        foreach ($tableList as $val) {
            $sql = "show create table " . $val;
            $res = $model->query($sql);
            $info = "-- ----------------------------\r\n";
            $info .= "-- 表结构 `" . $val . "`\r\n";
            $info .= "-- ----------------------------\r\n";
            $sqlStr = $info . $res[0]['create table'] . ";\r\n\r\n";
            //追加到文件
            file_put_contents($fileName, $sqlStr, FILE_APPEND);
        }

        //将每个表的数据导出到文件
        foreach ($tableList as $val) {
            $sql = "select * from " . $val;
            $res = $model->query($sql);
            //如果表中没有数据，则继续下一张表
            if (empty($res)) {
                continue;
            }
            $info = "-- ----------------------------\r\n";
            $info .= "-- 表名`" . $val . "`\r\n";
            $info .= "-- ----------------------------\r\n";
            file_put_contents($fileName, $info, FILE_APPEND);
            //读取数据
            $sqlStr = "INSERT INTO `" . $val . "` VALUES ";
            foreach ($res as $value) {
                $sqlStr .= "(";
                foreach ($value as $v) {
                    $sqlStr .= "'" . $v . "', ";
                }
                //去掉最后一个逗号和空格
                $sqlStr = substr($sqlStr, 0, strlen($sqlStr) - 2);
                $sqlStr .= "),";
            }
            $sqlStr = trim($sqlStr, ',');
            $sqlStr = $sqlStr . ';';
            file_put_contents($fileName, $sqlStr, FILE_APPEND);
        }

        return $fileName;
    }

}
